package cn.hl.sfzy.controller;

import cn.hl.sfzy.util.Result;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName FileController
 * @Description TOOO
 * @Author Lilysi
 * @Date 2024//10//23//15:57
 * @Version 1.0
 */
@RestController
@CrossOrigin
public class FileController {

    private String realPath = "C:\\Users\\20924\\file";
//    private String realPath = "d:/file";

    @PostMapping("/upload")
    public Object upload( MultipartFile file) throws IOException {
        if(file.isEmpty()){ // 没有上传
            return Result.error();
        }
// 上传
// 获取文件名
        String filename = file.getOriginalFilename();
// 处理重名问题
        filename = UUID.randomUUID().toString()+filename;
// 上传
        file.transferTo(new File(realPath,filename));
        return Result.success(filename);
    }


    @RequestMapping("/downLoad")
    public void downLoad(String filename, HttpServletResponse response)
            throws IOException {
// 获取文件所属的真实路径
        File file = new File(realPath,filename);
// 组成字节输出流
        FileInputStream fin = new FileInputStream(file);
// 设置响应头信息
        response.setHeader("Content-Disposition", "filename="+filename);//预览

// 组成相应流
        ServletOutputStream out = response.getOutputStream();
// 拷贝
        IOUtils.copy(fin,out);
// 释放资源
        out.close();
        fin.close();
    }
}
